package com.app.ui.pager.home;

import android.view.LayoutInflater;
import android.view.View;

import com.app.net.res.mood.Mood;
import com.app.net.res.user.User;
import com.app.ui.activity.base.BaseActivity;
import com.app.ui.activity.mood.MoodAddActivity;
import com.app.ui.adapter.mood.MoodAdapter;
import com.app.ui.event.MoodEvent;
import com.app.ui.pager.BaseViewPager;
import com.app.ui.view.list.swipe.RefreshMoreList;
import com.app.utiles.other.ActivityUtile;
import com.app.utiles.other.ToastUtile;
import com.wxj.zx.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

/**
 * 心情
 * Created by Administrator on 2016/9/7.
 */
public class HomeMoodPager extends BaseViewPager {


    @Bind(R.id.lv)
    RefreshMoreList lv;
    private MoodAdapter adapter;


    public HomeMoodPager(BaseActivity baseActivity) {
        super(baseActivity);
    }

    @Override
    protected View onViewCreated() {
        View view = LayoutInflater.from(baseActivity).inflate(R.layout.pager_home_mood, null);
        ButterKnife.bind(this, view);
        lv.setOnLoadingListener(new LoadingListener());
        lv.setLoadMore(false);
        adapter = new MoodAdapter();
        lv.setAdapter(adapter);
        lv.onRefreshing();
        EventBus.getDefault().register(this);
        return view;
    }


    @OnClick(R.id.mood_add_iv)
    public void onViewClicked() {
        ActivityUtile.startActivityCommon(MoodAddActivity.class);
    }

    class LoadingListener implements RefreshMoreList.OnLoadingListener {

        @Override
        public void onLoading(boolean isRefresh) {
            getMood();
        }
    }

    private void getMood() {
        User user = baseApplication.getUser();
        BmobQuery<Mood> query = new BmobQuery<>();
        query.addWhereEqualTo("userObjectId", user.getObjectId());
        query.findObjects(baseActivity, new Listener());
    }

    class Listener extends FindListener<Mood> {

        @Override
        public void onSuccess(List<Mood> list) {
            dialogDismiss();
            adapter.setData(list);
            lv.onRenovationComplete();
        }

        @Override
        public void onError(int i, String s) {
            dialogDismiss();
            ToastUtile.showToast("获取数据失败");
            lv.onRenovationComplete();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnBack(MoodEvent moodEvent) {
        if (!moodEvent.toCompareTag(this)) {
            return;
        }
        lv.onRefreshing();
    }

    @Override
    public void onDestory() {
        EventBus.getDefault().unregister(this);
        super.onDestory();
    }
}
